package team1.project2.vmlogs;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VmlogsUtils {
	public static SimpleDateFormat	f = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

	public static Date getUTCTime(String dateTimeStr) throws ParseException {
		dateTimeStr = dateTimeStr.replace("T", " ");
		dateTimeStr = dateTimeStr.substring(0,
		        findNthIndexOf(dateTimeStr, "\\.", 1));
		Calendar aUCTCalendar = Calendar.getInstance(TimeZone.getTimeZone("Z"));
		aUCTCalendar.setTime(f.parse(dateTimeStr));
		
		// System.out.println("dateTimeStr="+dateTimeStr);
		// System.out.println(f.format(new Date()));
		
		return aUCTCalendar.getTime();
	}
	
	public static Date getUTCTime2(String dateTimeStr) throws ParseException {
		dateTimeStr = dateTimeStr.replace("T", " ");
		dateTimeStr = dateTimeStr.substring(0,dateTimeStr.length()-1);
		Calendar aUCTCalendar = Calendar.getInstance(TimeZone.getTimeZone("Z"));
		aUCTCalendar.setTime(f.parse(dateTimeStr));
		
		// System.out.println("dateTimeStr="+dateTimeStr);
		// System.out.println(f.format(new Date()));
		
		return aUCTCalendar.getTime();
	}

	public static int findNthIndexOf(String str, String needle, int occurence)
	        throws IndexOutOfBoundsException {
		int index = -1;
		Pattern p = Pattern.compile(needle, Pattern.MULTILINE);
		Matcher m = p.matcher(str);
		while (m.find()) {
			if (--occurence == 0) {
				index = m.start();
				break;
			}
		}
		if (index < 0)
			throw new IndexOutOfBoundsException();
		return index;
	}
}
